#include "map_fs.h"

void loadMap_toSD(Level *p, int i)
{
    //FATFS SD_0;
    FRESULT frl;
    FIL mapData;

    // frl = f_mount(&SD_0, "0:", 1);
    // if (frl == FR_OK)
    //     UART_printf(&huart1, "SD mount OK!\r\n");
    // else
    //     UART_printf(&huart1, "SD mount error = %d\r\n", frl);
    //构建路径
    char path[32], num[8];
    strcpy(path, "0:level");
    sprintf(num, "%d", i);
    strcat(path, num);
    strcat(path, ".bat");

    frl = f_open(&mapData, path, FA_CREATE_ALWAYS | FA_WRITE | FA_READ);
    if (frl == FR_OK)
        UART_printf(&huart1, path);
    else
        UART_printf(&huart1, "file open error = %d\r\n", frl);
    
    frl = f_write(&mapData, p, sizeof(Level)-sizeof(&p), NULL);
    if (frl == FR_OK)
        UART_printf(&huart1, "%d\n",sizeof(Level)-sizeof(&p));
    else
        UART_printf(&huart1, "file write error = %d\r\n", frl);
    
    f_close(&mapData);

    if (frl == FR_OK) {
        UART_printf(&huart1, "Doc Close OK!\r\n");
    } else
        UART_printf(&huart1, "Doc Close error = %d\r\n", frl);

    // f_mount(NULL, "0:", 1);
}
void readMap_fromSD(Level *p, int i)
{
    //FATFS SD_0;
    FRESULT frr;
    FIL mapData;

    // frr = f_mount(&SD_0, "0:", 1);
    // if (frr == FR_OK)
    //     UART_printf(&huart1, "SD mount OK!\r\n");
    // else
    //     UART_printf(&huart1, "SD mount error = %d\r\n", frr);

    //构建路径
    char path[32], num[8];
    strcpy(path, "0:level");
    sprintf(num, "%d", i);
    strcat(path, num);
    strcat(path, ".bat");

    frr = f_open(&mapData, path, FA_READ);
    if (frr == FR_OK)
        UART_printf(&huart1, path);
    else
        UART_printf(&huart1, "file open error = %d\r\n", frr);

    frr = f_read(&mapData, p, sizeof(Level)-sizeof(&p), NULL);
    if (frr == FR_OK)
        UART_printf(&huart1, "%d\n",sizeof(Level)-sizeof(&p));
    else
        UART_printf(&huart1, "file read error = %d\r\n", frr);

    f_close(&mapData);
    if (frr == FR_OK) {
        UART_printf(&huart1, "Doc Close OK!\r\n");
    } else {
        UART_printf(&huart1, "'Doc Close error = %d\r\n", frr);
    }

    // f_mount(NULL, "0:", 1);
}